package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class ToolDB {
	public static DataSource ds = getDs();

	private static DataSource getDs() {
		try {
			Context ic = new InitialContext();
			DataSource ds = (DataSource) ic.lookup("java:comp/env/jdbc/news");
			return ds;
		} catch (NamingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Connection open() {
		Connection con = null;
		try {
			con = ds.getConnection();
			return con;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void close(Statement st, Connection con, ResultSet rs) {
		close(st);
		close(con);
		close(rs);
	}

	public static void close(Statement st) {
		if (st != null) {
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void close(Connection con) {
		if (con != null) {
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void close(ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public int executeUpdate(String sql, Object... args) {
		Connection con = open();
		PreparedStatement ps = null;
		try {
			ps = con.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i + 1, args[i]);
			}
			return ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			close(null, con, null);
		}
	}
}
